package com.toocms.jinjuhang.ui.mine.succour

import android.app.Application
import android.os.Bundle
import androidx.core.graphics.drawable.DrawableCompat
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ResourceUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.AddressDetailsData
import com.toocms.jinjuhang.data.goods.RescueDetailData
import com.toocms.jinjuhang.dialog.options.OptionsItem
import com.toocms.jinjuhang.ui.commodity.detils.CommodityDetailsFgt
import com.toocms.jinjuhang.ui.mine.receiver_address.ReceiverAddressFgt
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.base.MultiItemViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.Messenger

class ApplySuccourModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    val backIconObservableField by lazy {
        val backDrawable = ResourceUtils.getDrawable(R.mipmap.icon_arrow_left_black).mutate()
        DrawableCompat.setTint(backDrawable, 0xFFFFFFFF.toInt())
        ObservableField(backDrawable)
    }

    val rescueId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_REFUND_ID) ?: ""
    }

    val backClickBindingCommand = BindingCommand<BindingAction>(this::finishFragment)

    val dataObservableField = ObservableField<RescueDetailData>()

    val addressObservableField = ObservableField<AddressDetailsData>()

    val params = ObservableArrayList<MultiItemViewModel<*>>()

    //TODO 添加类型params()方法需要修改添加该类型
    val paramsItemBinding = ItemBinding.of<MultiItemViewModel<*>> { itemBinding, _, item ->
        when (item.itemType) {
            Constants.RecyclerViewItemType.ITEM_TYPE_ZERO -> itemBinding.set(
                BR.applySuccourParamInputItemModel, R.layout.item_apply_succour_param_input
            )
            Constants.RecyclerViewItemType.ITEM_TYPE_ONE -> itemBinding.set(
                BR.applySuccourParamOptionItemModel, R.layout.item_apply_succour_param_option
            )
            Constants.RecyclerViewItemType.ITEM_TYPE_TWO -> itemBinding.set(
                BR.applySuccourParamImageItemModel, R.layout.item_apply_succour_param_image
            )
        }
    }

    val commodityClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        dataObservableField.get()?.goods?.apply {
            val bundle = Bundle()
            bundle.putString(Constants.BundleKey.KEY_GOODS_ID, goods_id)
            this@ApplySuccourModel.startFragment(CommodityDetailsFgt::class.java, bundle)
        }
    })

    val addressClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val bundle = Bundle()
        bundle.putString(Constants.BundleKey.KEY_ACTION, Constants.Extra.ACTION_ACQUIRE)
        startFragment(ReceiverAddressFgt::class.java, bundle)
    })

    val immediatelyDeclareClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["address_id"] = addressObservableField.get()?.adr_id
        params["rescue_id"] = rescueId
        params["params"] = params()
        requestData(Urls.Goods.RESCUE_APPLY, params, resultClass = String::class.java, result = {
            showToast(it)
            finishFragment()
        })
    })

    init {
        requestData()
        initializeMessenger()
    }

    private fun initializeMessenger() {
        Messenger.getDefault().register(
            this, Constants.MessengerToken.TOKEN_ADDRESS, AddressDetailsData::class.java
        ) {
            addressObservableField.set(it)
        }
    }


    private fun params(): String {
        val result = StringBuilder()
        params.forEach { item ->
            var content: String? = null
            when (item) {
                is ApplySuccourParamOptionItemModel -> {
                    content =
                        "{\"title\":\"${item.titleObservableField.get()}\",\"value\":\"${item.contentObservableField.get()}\",\"type\":\"${item.type}\"}"
                }
                is ApplySuccourParamInputItemModel -> {
                    content =
                        "{\"title\":\"${item.titleObservableField.get()}\",\"value\":\"${item.contentObservableField.get()}\",\"type\":\"${item.type}\"}"
                }
                is ApplySuccourParamImageItemModel -> {
                    content =
                        "{\"title\":\"${item.titleObservableField.get()}\",\"value\":\"${item.id}\",\"type\":\"${item.type}\"}"
                }
            }
            if (content.isNullOrEmpty()) return@forEach
            if (result.isNotEmpty()) result.append(",")
            result.append(content)
        }
        return "[$result]"
    }

    private fun requestData() {
        requestData(Urls.Goods.RESCUE_DETAIL,
            mapOf(Pair("rescue_id", rescueId)),
            resultClass = RescueDetailData::class.java,
            isShowLoading = true,
            result = {
                dataObservableField.set(it)
                params.clear()
                it.params?.forEach {
                    when (it.type) {
                        "1" -> { //文字
                            params += ApplySuccourParamInputItemModel(
                                this, it.type, ObservableField(it.title)
                            )
                        }
                        "2" -> { //图片
                            params += ApplySuccourParamImageItemModel(
                                this, it.type, ObservableField(it.title)
                            )
                        }
                        "3" -> { //选项
                            val optionsItems = ArrayList<OptionsItem>()
                            it.options?.forEach {
                                optionsItems += object : OptionsItem {
                                    override fun title() = it

                                }
                            }
                            params += ApplySuccourParamOptionItemModel(
                                this, it.type, ObservableField(it.title), optionsItems
                            )
                        }
                    }
                }
            })
    }
}